package frontend.components.base;

import frontend.components.other.UserInputCallableAction;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.util.CollectionModel;

import java.util.List;

public class DropDownComponent<ModelType, EntityType> extends Panel {
    public DropDownComponent(String propertyId, String labelResourceKey, ModelType uiModel, final List<EntityType> availableOptions,
                             IChoiceRenderer<EntityType> choiceRender, boolean isNullValid, final UserInputCallableAction<EntityType> onSelectAction) {
        this(propertyId, labelResourceKey, uiModel, new CollectionModel(availableOptions), choiceRender, isNullValid, onSelectAction);
    }

    public DropDownComponent(String propertyId, String labelResourceKey, ModelType uiModel, CollectionModel availableOptionsCollectionModel,
                             IChoiceRenderer<EntityType> choiceRender, boolean isNullValid, final UserInputCallableAction<EntityType> onSelectAction) {
        super(propertyId);
        Label label = new Label("label", new ResourceModel(labelResourceKey));
        final DropDownChoice<EntityType> dropDown = new DropDownChoice<EntityType>("dropDown", new PropertyModel<EntityType>(uiModel, propertyId),
                availableOptionsCollectionModel, choiceRender);
        dropDown.setNullValid(isNullValid);
        dropDown.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                if (onSelectAction != null) {
                    EntityType selectedValue = dropDown.getModelObject();
                    onSelectAction.call(target, selectedValue);
                }
            }
        });
        List availableOptions = (List) availableOptionsCollectionModel.getObject();
        if (!isNullValid && availableOptions.size() == 1) {
            dropDown.setDefaultModelObject(availableOptions.get(0));
        }
        add(label, dropDown);
        setOutputMarkupId(true);
    }
}
